package middleware

import (
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"user/api/internal/types"
	"user/pkg"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		if token == "" {
			resp := types.Response{
				Message: "未登录",
				Code:    500,
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		getToken, s := pkg.GetToken(token)
		if s != "" {
			resp := types.Response{
				Message: s,
				Code:    500,
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		fmt.Println(token)
		r.ParseForm()
		r.Form.Set("userId", getToken["userId"].(string))
		// Passthrough to next handler if need
		next(w, r)
	}
}
